import { fetchDict } from '@/redux/dict/dict-api';
import { fetchUsers, getRole } from '@/redux/user/user-api';
import { IRootReducerState } from '@/store/root-reducer';
import { Button, Form } from '@douyinfe/semi-ui';
import Section from '@douyinfe/semi-ui/lib/es/form/section';
import { debounce } from 'lodash';
import { useEffect, useMemo, useRef, useState } from 'react';
import { shallowEqual, useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';

const UserEdit = ({
  entity,
  persistEntity,
  formApiRef,
}: {
  entity?: any;
  persistEntity?: (entity: any) => void;
  formApiRef?: (value: any) => void;
}) => {
  const [businessType, setAllBusinessType] = useState<any[]>([]);
  const message = '该项为必填项';
  const formRef = useRef();
  const { user } = useSelector<IRootReducerState, any>(
    (state) => ({ user: state.user }),
    shallowEqual
  );
  const { entities, totalCount, actionsLoading } = user;
  const dispatch = useDispatch<any>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<any[]>([]);
  const [roleList, setRoleList] = useState<any[]>([]);

  useEffect(() => {
    fetchDict({
      pageNum: 1,
      pageSize: 999,
      dictionaryType: 'BUSINESS_TYPE',
    }).then((res) => {
      setAllBusinessType(res.data.content);
    });
    getRole().then((res: any) => {
      setRoleList(res.data);
    });
  }, []);
  useEffect(() => {
    return () => {};
  }, []);

  const handleSearch = (inputValue: string) => {
    setLoading(true);
    let result: any[] = [];
    if (inputValue) {
      fetchUsers({
        key: inputValue,
      }).then((res: any) => {
        setLoading(false);

        setList(
          res.data.map((item: any, index: number) => {
            return {
              value: item.name,
              label: `${item.name}-${item.code}`,
              item,
            };
          })
        );
      });
    } else {
      setLoading(false);
    }
  };

  const initialValue = useMemo(() => {
    const value = { ...entity };
    if (entity?.businessType) {
      value.businessTypeList = entity.businessType.split(',');
    }

    if (entity?.roleList) {
      value.roleIdList = entity.roleList.map((role: any) => role?.id);
    }
    return value;
  }, [entity]);

  useEffect(() => {
    if (!entity?.id) return;
    const initialUser = {
      value: entity?.name,
      label: `${entity.name}-${entity.code}`,

      item: {
        code: entity?.code,
        corporation: entity?.corporation,
        department: entity?.department,
        email: entity?.email,
        name: entity?.name,
      },
    };
    setList([initialUser]);
    //@ts-ignore
    formRef.current.formApi.setValue('name', initialUser);
  }, [entity]);

  const handleSelectChange = (newValue: any) => {
    //@ts-ignore
    formRef.current.formApi.setValue('code', newValue.item.code);
    //@ts-ignore
    formRef.current.formApi.setValue('corporation', newValue.item.corporation);
    //@ts-ignore
    formRef.current.formApi.setValue('department', newValue.item.department);
    //@ts-ignore
    formRef.current.formApi.setValue('email', newValue.item.email);
  };

  return (
    <Form
      //@ts-ignore
      ref={formRef}
      getFormApi={(api: any) => formApiRef && formApiRef(api)}
      validateFields={() => ''}
      onSubmit={(values: any) => {
        const submitValues = { ...values };
        if (submitValues?.name) {
          submitValues.name = values?.name?.value;
        }
        if (submitValues?.businessTypeList) {
          submitValues.businessType = values?.businessTypeList.join(',');
        }
        if (submitValues?.id) {
          submitValues.userId = values?.id;
        }

        persistEntity && persistEntity(submitValues);
      }}
      initValues={initialValue}
    >
      <Form.Select
        field='name'
        label='用户姓名'
        style={{ width: '100%' }}
        placeholder='请输入用户姓名或工号'
        disabled={entity?.id}
        filter
        remote
        onChangeWithObject
        onSearch={debounce(handleSearch, 1000)}
        optionList={list}
        loading={loading}
        emptyContent={null}
        onChange={handleSelectChange}
        rules={[{ required: true, message }]}
        validate={(fieldValue, values) => {
          if (!fieldValue || fieldValue?.length === 0) {
            return '请选择用户';
          }
          return '';
        }}
      ></Form.Select>
      <Form.Input
        disabled
        field='code'
        label='工号'
        placeholder='工号'
      ></Form.Input>
      <Form.Input
        disabled={!entity?.id}
        field='corporation'
        label='所属企业'
        placeholder='所属企业'
      ></Form.Input>
      <Form.Input
        disabled
        field='department'
        label='部门'
        placeholder='部门'
      ></Form.Input>
      <Form.Input
        disabled
        field='email'
        label='邮箱'
        placeholder='邮箱'
      ></Form.Input>
      {entity?.id && (
        <>
          <Form.Input
            field='phoneNumber'
            label='联系方式'
            placeholder='联系方式'
            validate={(fieldValue, values) => {
              if (!fieldValue || fieldValue?.length === 0) {
                return '';
              }
              console.log(/^(?:(?:\+|00)86)?1\d{10}$/.test(fieldValue));
              if (!/^(?:(?:\+|00)86)?1\d{10}$/.test(fieldValue)) {
                return '手机号格式错误';
              }
              return '';
            }}
          ></Form.Input>
          <Form.Select
            label='业务范围'
            field='businessTypeList'
            placeholder='请选择业务范围'
            trigger='blur'
            showClear
            multiple
            style={{ width: '100%' }}
          >
            {businessType?.map((type: any, idx: any) => (
              <Form.Select.Option
                key={`type_${idx}`}
                value={type?.dictionaryKey}
              >
                {type?.dictionaryKey}
              </Form.Select.Option>
            ))}
          </Form.Select>
          <Form.Select
            label='用户角色'
            field='roleIdList'
            placeholder='请选择用户角色'
            trigger='blur'
            showClear
            multiple
            style={{ width: '100%' }}
          >
            {roleList?.map((role: any, idx: any) => (
              <Form.Select.Option key={`role_${idx}`} value={role?.id}>
                {role?.name}
              </Form.Select.Option>
            ))}
          </Form.Select>
        </>
      )}
      <div className='w-full flex justify-end items-center py-4 '>
        <Button onClick={() => navigate(-1)}>取消</Button>
        <Button
          theme='solid'
          htmlType='submit'
          className='mx-2'
          disabled={actionsLoading}
        >
          保存
        </Button>
      </div>
    </Form>
  );
};

export default UserEdit;
